<?php

namespace App\Http\Controllers;

use App\Http\Models\Comment;
use App\Http\Models\Post;
use App\Http\Models\Zan;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    protected function learn()
    {
        // 0 首先注册[driver]驱动,标识符[driver] [singleton('log', $monolog)]
        // Application.php->registerCoreContainerAliases 中定义了默认alias依赖解析注入规则,
        // 定义了哪些类在依赖注入解析的时候,可以解析为[driver]标识符对应的[driver]驱动

        // 1 从服务容器中取出[driver]对象
        $cache = app('cache');
        $cache->put('cache', time());

        // 2 利用门脸类静态调用[driver]对象方法
        // Facade本身定义静态调用解析规则[对应哪个driver]
        \Illuminate\Support\Facades\Cache::put('cache', time());

        // 3 直接从全局命名空间中取
        // config/app.aliases 定义了facade的全局简称
        \Cache::put('cache', time());


        /**
         * ElasticSearch ES搜索引擎
         * [索引(index)] [类型(type)] [文档(document)] [字段(field)] [模板(template)]
         * [数据库]       [数据表]     [数据行]         [数据表字段]   [定义搜索规则]
         */
        /**
         * ElasticSearch 安装
         * @link https://gitee.com/wang3960/elasticsearch-rtf
         * 使用 bin/elasticsearch-plugin remove xxx 删除插件(只保留ik插件)
         * 启动: elasticsearch.bat
         * @copyright 127.0.0.1:9300 127.0.0.1:9200
         *
         * ElasticSearch laravel驱动
         * @help https://learnku.com/docs/laravel/5.4/scout/1276
         * composer require laravel/scout
         *
         * 发布配置,自动添加控制器等代码
         * php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
         *
         * 安装 laravel-scout-elastic
         * composer require tamayo/laravel-scout-elastic 3.*.*
         * composer require guzzlehttp/guzzle 6.*.*  [使用http配置es]
         * @link https://github.com/ErickTamayo/laravel-scout-elastic
         *
         * 创建自定义命令行,http,配置es_template
         * php artisan make:command ESInit
         *
         * 定义导入模型并执行导入
         * php artisan scout:import "\App\Http\Models\Post"
         * (模型配置好后,后续会自动同步到ES)
         */

        return view('post.index');
    }
    
    // 列表页面
    public function index()
    {
        $posts = Post::query()->withCount(['comments', 'zans'])->with(['user'])->latest()->paginate(10);
        return view('post.index', compact('posts'));
    }

    // 详情页
    public function show(Post $post)
    {
        // 预加载,减少查询次数
        $post->load('comments');
        return view('post.show', compact('post'));
    }

    // 创建文章
    public function create()
    {
        return view('post.create');
    }

    // 保存文章
    public function store(\Illuminate\Http\Request $request)
    {
        // 获取request指定参数
        // $params = \request(['name', 'title']);
        // $post = Post::create(\request(['title', 'content']));

        // 表单验证
        $rules = [
            'title' => 'required|string|min:3',
            'content' => 'required|string|min:3',
        ];
        $this->validate($request, $rules);

        // 保存数据
        $user_id = Auth::id();
        $params = array_merge(request(['title', 'content']), compact('user_id'));
        Post::create($params);

        // 重定向到列表页
        return redirect('/posts');
    }
    
    // 编辑页面
    public function edit(Post $post)
    {
        return view('post.edit', compact('post'));
    }

    // 编辑文章
    public function update(Post $post, \Illuminate\Http\Request $request)
    {
        // 验证
        $rules = [
            'title' => 'required|string|min:3',
            'content' => 'required|string|min:3',
        ];
        $this->validate($request, $rules);

        // 权限
        // php artisan make:policy PostPolicy
        $this->authorize('update', $post);

        // 保存
        $post->title = $request->input('title');
        $post->content = $request->input('content');
        $post->save();

        // 渲染
        return redirect("/posts/{$post->id}");
    }

    // 删除文章
    public function delete(Post $post)
    {
        // 权限
        $this->authorize('delete', $post);

        $post->delete();

        return redirect('posts');
    }

    // 提交评论
    public function comment(Post $post, \Illuminate\Http\Request $request)
    {
        // 验证
        $rules = [
            'content' => 'required|string|min:3',
        ];
        $this->validate($request, $rules);

        // 关联模型保存
        $comment = new Comment();
        $comment->content = $request->input('content');
        $comment->user_id = Auth::id();
        $post->comments()->save($comment);

        // 渲染
        return redirect()->back();
    }

    // 赞
    public function zan(Post $post)
    {
        // 保存
        $params = [
            'user_id' => Auth::id(),
            'post_id' => $post->id,
        ];
        Zan::query()->firstOrCreate($params);

        // 渲染
        return redirect()->back();
    }

    // 取消赞
    public function unzan(Post $post)
    {
        // 关联模型的删除
        $post->zan(Auth::id())->delete();

        // 渲染
        return redirect()->back();
    }

    public function search(\Illuminate\Http\Request $request)
    {
        // 验证
        /* @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($request->toArray(), ['query' => 'required']);
        if ($validator->fails()) {
            return redirect('/posts');
        }

        // 保存
        $query = $request->input('query');
        $posts = Post::search($query)->paginate(10);

        // 渲染
        return view('post.search', compact('posts', 'query'));
    }

    protected function note()
    {
        // make 表示生成 , create 表示存入数据库
        $list = factory(\App\Http\Models\Post::class, 10)->make();

        // $list = factory(\App\Http\Models\Post::class, 100)->create();
        return json_encode($list);

        // 链接public与storage
        // php artisan storage:link
    }

    public function imageUpload(\Illuminate\Http\Request $request)
    {
        // 获取和验证文件
        $file = $request->file('wangEditorH5File');
        if ($file->getError() > 0) {
            return $file->getErrorMessage();
        }

        // 存储并获得路径
        // 921122b7c7d42d7b1afb3758eef1a545/zpQVdso85yYuGLK3kU1g5kvGrreYRcDk3OVbsjd1.jpeg
        $path = $file->storePublicly(md5($file->getBasename() . microtime(true)));


        // 返回url路径[asset]
        // asset: http://127.0.0.1:8000/
        // 结果: http://127.0.0.1:8000/storage/921122b7c7d42d7b1afb3758eef1a545/zpQVdso85yYuGLK3kU1g5kvGrreYRcDk3OVbsjd1.jpeg
        return asset('storage/' . $path);
    }
}
